package com.yang.sso.oauth.oauth.converter;

import com.yang.sso.oauth.model.MyUserDetails;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 自定义用户身份转换器
 *
 * @author: Islands
 * @create: 2024-04-11 22:17
 */

@Configuration
public class CustomerAccessTokenConverter extends DefaultUserAuthenticationConverter {


    @Override
    public Map<String, ?> convertUserAuthentication(Authentication authentication) {
        Map<String, Object> response = new LinkedHashMap<String, Object>();
        response.put("username", authentication.getName());
        Object principal = authentication.getPrincipal();
        if(principal instanceof MyUserDetails){
            MyUserDetails userDetails = (MyUserDetails) principal;
            response.put("userId",userDetails.getUserId());
            response.put("nickname",userDetails.getNickname());
            response.put("avatar",userDetails.getAvatar());
            response.put("enabled",userDetails.getEnabled());
            response.put("roles",userDetails.getRoles());
        }
        if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
            response.put("authorities", AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
        }
        return response;
    }
}
